<template>
  <div>
    <div class="inspection-container">
      <!-- 搜索栏 -->
      <div class="sickness-page-form">
        <el-input
          style="width: 300px"
          placeholder="请输入内容"
          v-model="formData.templateName"
          :disabled="selectedGroup.activeName_1 != '1'"
        />
        <el-button
          type="primary"
          @click="addDepApi"
          v-if="selectedGroup.activeName_1 == '1'"
          >保存</el-button
        >
      </div>
      <div>
        <TagInput
          @add-tag="addTag"
          :recomScene="recomScene"
          :isNone="selectedGroup.activeName_1"
        />
      </div>
      <!-- 表格组件 -->
      <!-- 表格组件 -->
      <inspectionTemplate
        title="查验项目"
        ref="inspectionTemplateRef"
        :tableData="tableData"
        :frequencyOptions="frequency"
        :fieldList="formData.fieldList"
        :activeName_1="selectedGroup.activeName_1"
        :defaultActiveType="'inspection'"
        @update:tableData="updateTableData"
        @active-type-change="handleActiveTypeChange"
        @row-update="updateRow"
        @search-result-select="handleSearchResultSelect"
      />
      <div style="height: 350px">
        <!-- 底部留白 -->
      </div>
      <!-- 检验 -->
      <div>
        <el-dialog
          v-model="dialogVisible"
          class="custom-transition-dialog"
          width="50%"
        >
          <Examine
            :activeType="activeType"
            :tableData="tableData"
            :frequencyOptions="frequency"
            @updateRow="updateRow"
            @close="onCloseExamine"
            @confirm="handleExamineConfirm"
          />
        </el-dialog>
      </div>
    </div>
    <div>
      <div
        class="modal-footer relative"
        v-if="selectedGroup.activeName_1 == '1'"
      >
        <el-button
          style="float: right; margin-top: 25px; margin-right: 27px"
          type="primary"
          @click="onAddTemplate"
          >确定</el-button
        >
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import TagInput from './TagInput.vue';
import inspectionTemplate from './inspectionTemplate.vue';
import {
  addTemplateInspection,
  updateTemplateInspection,
} from '@/api/formwork';
import stores from '@/store';

const useBaseData = stores.useBaseDataStore();
const frequency = ref(useBaseData.getDictsSelect('FREQUENCY'));
const recomScene = ref<string>('');
const formData = ref<any>({
  fieldList: [],
  templateName: '',
  templateType: '1',
  recomScene: '',
  groupId: '',
});
// 外治处方数据
const emit = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: 'inspection' | 'examination'];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
  updataTemplate: [];
  refresh: [];
}>();
const tableData = ref<InspectionItem[]>([
  {
    examId: 1,
    name: '肝功能',
    category: '检查',
    frequency: '1天1次',
    period: 1,
    totalCount: 1,
    remark: '悬停可删除',
  },
  {
    examId: 2,
    name: '血常规',
    category: '检验',
    frequency: '3天1次',
    period: 3,
    totalCount: 1,
    remark: '',
  },
  {
    examId: 3,
    name: '尿常规',
    category: '检验',
    frequency: '1周1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
  {
    examId: 3,
    name: '尿常规',
    category: '检验',
    frequency: '1周1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
  {
    examId: 4,
    name: 'CT检查',
    category: '检查',
    frequency: '1月1次',
    period: 1,
    totalCount: 1,
    remark: '',
  },
]);
const inspectionTemplateRef = ref<InstanceType<typeof inspectionTemplate>>(); // 检验项目的ref获取检验项目数据
const selectedGroup = defineProps<{
  selectedGroupId: any;
  templateMedicalDetail: any;
  dataType: string;
  activeName_1: string;
}>();
// 定义数据类型
interface InspectionItem {
  examId: number;
  name: string;
  category: '检验' | '检查';
  frequency: string;
  period: number;
  totalCount: number;
  remark: string;
  isNew?: boolean;
  projectId?: number; // 主键ID
  projectName?: string; // 项目名称;CT
  price?: number; // 价格
  projectCategory?: string; // 项目分类;1检查2.检验3.治疗 projectCategoryEnum
  projectCategoryName?: string; // 项目分类名称
  projectType?: string; // 项目类型;头部CT 如果projectCategory=1取字典中的EXAM_TYPE,projectCategory=2取LAB_TYPE，如果等于3取EXT_TYPE
  sampleType?: string; // 样本类型;如果是检验项目需要维护1.全血 sampleTypeEnum
  chargeType?: string; // 收费类型1项目2穴位 ProjectChargeTypeEnum
  unit?: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
  unitName?: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
}
watch(
  () => selectedGroup,
  (newVal) => {
    if (selectedGroup.dataType == '1') {
      tableData.value = [];
    } else {
      tableData.value = selectedGroup.templateMedicalDetail.detailList || [];
      formData.value.templateName =
        selectedGroup.templateMedicalDetail.templateName || '';
      formData.value.recomScene =
        selectedGroup.templateMedicalDetail.recomScene || '';
      recomScene.value = selectedGroup.templateMedicalDetail.recomScene || '';
    }
    //console.log(selectedGroup.templateMedicalDetail.detailList);
    formData.value.templateId = selectedGroup.templateMedicalDetail.templateId;
    formData.value.groupId = newVal;
  },
  { immediate: true, deep: true }
);
// 响应式数据
const activeType = ref<any>('');
const dialogVisible = ref(false);

// 表格数据

// 方法
const setActiveType = (type: 'inspection' | 'examination') => {
  activeType.value = type;
  dialogVisible.value = true;
};
// 弹框添加事件
const handleExamineConfirm = (selectedList: any[]) => {
  // 将选中项合并到tableData，避免重复
  const existIds = new Set(tableData.value.map((item) => item.examId));
  const newItems = selectedList.filter(
    (item) => !existIds.has(item.id || item.examId)
  );
  tableData.value = [...tableData.value, ...newItems];
};
// 处理表格组件事件
const updateTableData = (newData: any) => {
  tableData.value = newData;
};

const handleActiveTypeChange = (type: 'inspection' | 'examination') => {
  activeType.value = type;
  dialogVisible.value = true;
};

//选择模板
const onAddTemplate = () => {
  // templateDialog.value = true;
  emit('updataTemplate');
};
const updateRow = (row: any, index: number) => {
  // 当编辑现有行时，自动保存更改
  if (!row.isNew) {
    tableData.value[index] = { ...row };
    //console.log(tableData.value, 'tableData');
    emit('update:tableData', tableData.value);
    ElMessage.success('数据已更新');
  }
};

const handleSearchResultSelect = (result: any) => {
  //console.log('选择了搜索结果:', result);
  // 处理搜索结果选择逻辑
};

const addTag = (tags: string[]) => {
  formData.value.recomScene = tags.join(',');
};

const onCloseExamine = () => {
  dialogVisible.value = false;
  activeType.value = '';
};
// 保存
const addDepApi = async () => {
  //console.log(tableData.value);
  //console.log(inspectionTemplateRef.value?.displayTableData);
  try {
    const tableData1 = inspectionTemplateRef.value?.displayTableData;

    // 验证必填字段
    if (!formData.value.templateName.trim()) {
      ElMessage.warning('请输入模板名称');
      return;
    }

    if (tableData1 && tableData1.length === 0) {
      ElMessage.warning('请至少添加一个检验项目');
      return;
    }

    // 准备提交数据 - 按照新的参数格式
    const submitData = {
      examList: tableData1?.map((item) => ({
        ...item,
        projectId: item.projectId || item.examId,
        frequencyCode: item.frequency, // 频率代码
        cycle: item.period, // 周期
        remark: item.remark || '', // 备注
        totalOutQty: item.totalCount, // 总量
      })),
      templateName: formData.value.templateName,
      groupId: selectedGroup.selectedGroupId,
      recomScene: formData.value.recomScene || '',
    };

    let response;
    //console.log(submitData, '提交的数据');

    // 根据 dataType 判断是新增还是编辑
    if (selectedGroup.dataType === '1') {
      // 新增
      const submitData = {
        examList: tableData1?.map((item) => ({
          ...item,
          remark: item.remark || '', // 备注
        })),
        templateName: formData.value.templateName,
        groupId: selectedGroup.selectedGroupId,
        recomScene: formData.value.recomScene || '',
      };
      response = await addTemplateInspection(submitData);
      if (response.code == '200') {
        formData.value = {
          fieldList: [],
          templateName: '',
          templateType: '1',
          recomScene: '',
          groupId: '',
        };
        tableData.value = [];
        emit('refresh');
        ElMessage.success('模板创建成功');

        // 关闭弹窗或执行其他操作
      } else {
        //ElMessage.error(response.msg);
      }
    } else if (selectedGroup.dataType === '2') {
      const submitData = {
        examList: tableData1?.map((item) => ({
          ...item,
        })),
        templateName: formData.value.templateName,
        groupId: selectedGroup.selectedGroupId,
        recomScene: formData.value.recomScene || '',
        templateType: selectedGroup.activeName_1,
        templateId: formData.value.templateId,
      };
      // 编辑 - 需要传入模板ID
      const updateData = {
        ...submitData,
      };
      response = await updateTemplateInspection(updateData);
      if (response.code == '200') {
        formData.value = {
          fieldList: [],
          templateName: '',
          templateType: '1',
          recomScene: '',
          groupId: '',
        };
        tableData.value = [];
        emit('refresh');
        ElMessage.success('模板更新成功');

        // 关闭弹窗或执行其他操作
      } else {
        //ElMessage.error(response.msg);
      }
    } else {
      ElMessage.warning('无效的操作类型');
      return;
    }

    //console.log('操作成功:', response);

    // 可以在这里添加成功后的回调，比如关闭弹窗、刷新列表等
    // emit('success', response);
  } catch (error) {
    //console.error('保存失败:', error);
    //ElMessage.error(selectedGroup.dataType === '1' ? '创建失败' : '更新失败');
  }
};
</script>
<style lang="scss" scoped>
.inspection-container {
  padding: 50px 20px 10px 20px;
  background-color: #fff;
  border-radius: 8px;
  height: 780px;
  overflow: auto;
}

::deep(.el-button) {
  margin: 0px !important;
}

.sickness-page-form {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 10px;
  justify-content: space-between;
}
</style>

<style lang="scss">
.custom-transition-dialog {
  padding: 0 !important;
  .el-dialog__header {
    padding: 16px 20px 0 20px;
    border-bottom: none;
  }
}
</style>
<style lang="scss">
.custom-transition-dialog {
  padding: 0 !important;
  .el-dialog__header {
    display: none;
  }
}
</style>
